import config from "./config";
import router from "@/router";
import axios from "axios";

axios.create({
  baseUrl: config.baseUrl,
  timeout: 0,
  withCredentials: true,
  responseType: "json",
  maxContentLength: 2000,
  transformResponse: [
    function(data) {
      //特殊处理逻辑
      //1. 验证跳转登录
      if (data && data.rs == "1211") {
        router.push("login");
      }
      //2. 其他
      return data;
    }
  ]
});

// 添加请求拦截器
axios.interceptors.request.use(
  function(config) {
    console.log("在发送请求之前做些什么?");
    return config;
  },
  function(error) {
    console.log("对请求错误做些什么?");
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  function(response) {
    console.log("对响应数据做点什么?");
    return response;
  },
  function(error) {
    console.log("对响应错误做点什么?");
    return Promise.reject(error);
  }
);

// get
export const _get = req => {
  return axios.get(req.url, { params: req.data });
};

// post
export const _post = req => {
  return axios({ method: "post", url: `/${req.url}`, data: req.data });
};

//patch
export const _put = req => {
  return axios({ method: "put", url: `/${req.url}`, data: req.data });
};

//delete
export const _delete = req => {
  return axios({ method: "delete", url: `/${req.url}`, data: req.data });
};

//post and no withCredentials
export const _postNoWithCredentials = req => {
  return axios({
    method: "post",
    url: `/${req.url}`,
    data: req.data,
    withCredentials: false
  });
};
